using System.Security.Cryptography;
using System.Text;
using Admin2025.Application.DTOs;
using Admin2025.Application.IServices;
using Admin2025.Domain.Common;
using Admin2025.Domain.Repositories;

namespace Admin2025.Application.Services;

public class UserService : IUserService
{
  private readonly IUserRepository _userRepository;

  public UserService(IUserRepository userRepository)
  {
    _userRepository = userRepository;
  }

  // 分页
  public async Task<PagedResult<UserDto>> GetUsersPagedAsync(PagedRequest request)
  {
    var result = await _userRepository.GetUsersPagedAsync(request);

    var items = result.Items.Select(u => new UserDto
    {
      UserId = u.Id,
      Username = u.UserName,
      Email = u.Email
    }).ToList();

    return new PagedResult<UserDto>
    {
      Items = items,
      TotalCount = result.TotalCount,
      PageNumber = result.PageNumber,
      PageSize = result.PageSize
    };
  }

  public async Task<UserDto?> GetUserByIdAsync(Guid userId)
  {
    var user = await _userRepository.GetByIdAsync(userId);
    return user == null ? null : new UserDto
    {
      UserId = user.Id,
      Username = user.UserName,
      Email = user.Email
    };
  }

  public async Task<IEnumerable<UserDto>> GetAllUsersAsync()
  {
    var users = await _userRepository.GetAllAsync();
    return users.Select(u => new UserDto
    {
      UserId = u.Id,
      Username = u.UserName,
      Email = u.Email
    });
  }

  public async Task<bool> UpdateUserAsync(Guid id, UpdateUserDto dto)
  {
    var user = await _userRepository.GetByIdAsync(id);
    if (user == null) return false;

    user.UserName = dto.Username;
    user.Email = dto.Email;
    // user.DepartmentId = dto.DepartmentId;

    if (!string.IsNullOrWhiteSpace(dto.Password))
    {
      user.PasswordHash = HashPassword(dto.Password);
    }

    await _userRepository.UpdateUserAsync(user);
    return true;
  }

  public async Task<bool> DeleteUserAsync(Guid id)
  {
    var user = await _userRepository.GetByIdAsync(id);
    if (user == null) return false;

    await _userRepository.DeleteUserAsync(id);
    return true;
  }

  private string HashPassword(string password)
  {
    using var sha256 = SHA256.Create();
    var bytes = Encoding.UTF8.GetBytes(password);
    var hash = sha256.ComputeHash(bytes);
    return Convert.ToBase64String(hash);
  }
}